package com.manning.readinglist.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;

import javax.sql.DataSource;

public class DataSourceBuilder {

	private static ResourceLoader loader = new DefaultResourceLoader();
	private static String MYBATIS_SETTING =  "classpath:/mybatis-config.xml";

	public static DataSource buildDataSource(DatasourceProperties properties) {
		DruidDataSource ds = new DruidDataSource();
		ds.setUrl(properties.getUrl());
		ds.setUsername(properties.getUsername());
		ds.setPassword(properties.getPassword());
		ds.setDriverClassName(properties.getDriverClassName());
		ds.setInitialSize(properties.getInitialSize());
		ds.setMaxActive(properties.getMaxActive());
		ds.setMinIdle(properties.getMinIdle());
		ds.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
		ds.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis());
		ds.setMaxWait(properties.getMaxWait());
		ds.setPoolPreparedStatements(properties.isPoolPreparedStatements());
		ds.setMaxOpenPreparedStatements(properties.getMaxOpenPreparedStatements());
		ds.setRemoveAbandoned(properties.isRemoveAbandoned());
		ds.setRemoveAbandonedTimeout(properties.getRemoveAbandonedTimeout());
		ds.setLogAbandoned(properties.isLogAbandoned());
		ds.setValidationQuery(properties.getValidationQuery());
		ds.setTestOnBorrow(properties.isTestOnBorrow());
		return ds;
	}

/*	public static SqlSessionFactoryBean buildSqlSessionFactory(DataSource dataSource, Interceptor offsetLimitIntercepter) {
		SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
		factory.setDataSource(dataSource);
		factory.setConfigLocation(loader.getResource(MYBATIS_SETTING));
		factory.setPlugins(new Interceptor[] { offsetLimitIntercepter });
		return factory;
	}*/
}
